package com.demo.sharedprefsdemo;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity {

    private SharedPreferences sp;
    private int count;
    private String loginTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sp = getSharedPreferences("login", Context.MODE_PRIVATE);
        count = sp.getInt("count", 0);
        String lastLoginTime = sp.getString("login_time", null);
        String loginInfo = "你已经登陆该软件" + (count + 1) + "次.";
        if (count > 0) {
            loginInfo += "你上次登陆的时间是 " + lastLoginTime;
        }
        Toast.makeText(this, loginInfo, Toast.LENGTH_LONG).show();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        loginTime = sdf.format(new Date());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt("count", count + 1);
        editor.putString("login_time", loginTime);
        editor.commit();
    }
}
